package com.huhao.smark;

import androidx.activity.OnBackPressedCallback;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.huhao.smark.Config.*;

public class SearchActivity extends AppCompatActivity {

    public static final String EXTRA_SEARCH_QUERY = "com.huhao.smark.EXTRA_SEARCH_QUERY";
    public static final int RESULT_OK = 1001;
    private List<String> suggestionList = KEYWORD_LIST;

    private AutoCompleteTextView autoCompleteTextView;
    private RecyclerView recyclerViewSuggestions;
    private SuggestionAdapter suggestionAdapter;

    private Map<String, Class<?>> keywordActivityMap = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        keywordActivityMap.put("关于", AboutActivity.class);
        keywordActivityMap.put("帮助与反馈", HelpFeedbackActivity.class);
        keywordActivityMap.put("通用设置", GeneralSettingsActivity.class);
        keywordActivityMap.put("功能介绍", FeaturesActivity.class);
        keywordActivityMap.put("账号与安全", AccountSecurityActivity.class);

        // 获取 AutoCompleteTextView 和 RecyclerView
        autoCompleteTextView = findViewById(R.id.autoCompleteTextView);
        recyclerViewSuggestions = findViewById(R.id.recyclerViewSuggestions);

        // 初始化 RecyclerView
        recyclerViewSuggestions.setLayoutManager(new LinearLayoutManager(this));
        suggestionAdapter = new SuggestionAdapter(new ArrayList<>());
        recyclerViewSuggestions.setAdapter(suggestionAdapter);

        // 设置输入框文本变化监听器
        autoCompleteTextView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 每次输入变化时，过滤联想建议并更新适配器数据
                String newText = s.toString();
                filterSuggestions(newText);
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });

        // 默认聚焦输入框并显示软键盘
        autoCompleteTextView.requestFocus();

        // 使用 OnBackPressedCallback 处理返回按键事件
        OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                finish();
            }
        };
        getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);

        // 初始化时加载初始联想词
        filterSuggestions("");
        recyclerViewSuggestions.setVisibility(View.VISIBLE); // 确保 RecyclerView 可见
    }

    private void filterSuggestions(String newText) {
        List<String> filteredSuggestions = new ArrayList<>();
        for (String suggestion : suggestionList) {
            if (suggestion.contains(newText)) {
                filteredSuggestions.add(suggestion);
            }
        }
        suggestionAdapter.updateData(filteredSuggestions);
        recyclerViewSuggestions.setVisibility(filteredSuggestions.isEmpty() ? View.GONE : View.VISIBLE);
    }

    // 联想词适配器
    private class SuggestionAdapter extends RecyclerView.Adapter<SuggestionAdapter.SuggestionViewHolder> {
        private List<String> suggestions;

        SuggestionAdapter(List<String> suggestions) {
            this.suggestions = suggestions;
        }

        void updateData(List<String> newSuggestions) {
            this.suggestions = newSuggestions;
            notifyDataSetChanged();
        }

        @Override
        public SuggestionViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.suggestion_item, parent, false);
            return new SuggestionViewHolder(view);
        }

        @Override
        public void onBindViewHolder(SuggestionViewHolder holder, int position) {
            holder.bind(suggestions.get(position));
        }

        @Override
        public int getItemCount() {
            return suggestions.size();
        }

        class SuggestionViewHolder extends RecyclerView.ViewHolder {
            private TextView suggestionTextView;

            SuggestionViewHolder(View itemView) {
                super(itemView);
                suggestionTextView = itemView.findViewById(R.id.suggestionTextView);
            }

            void bind(String suggestion) {
                suggestionTextView.setText(suggestion);
                // 点击联想词项时提交搜索
                itemView.setOnClickListener(v -> {
                    if ("个人主页".equals(suggestion)) {
                        Intent intent = new Intent(SearchActivity.this, MainActivity.class);
                        intent.putExtra("SHOW_PAGE", 2);
                        startActivity(intent);
                    } else if ("账本".equals(suggestion)) {
                        Intent intent = new Intent(SearchActivity.this, MainActivity.class);
                        intent.putExtra("SHOW_PAGE", 1);
                        startActivity(intent);
                    } else {
                        Class<?> targetActivity = keywordActivityMap.get(suggestion);
                        if (targetActivity != null) {
                            Intent intent = new Intent(SearchActivity.this, targetActivity);
                            startActivity(intent);
                        }
                    }
                    finish();
                });
            }
        }
    }
}